<?php

namespace App\Http\Controllers\Api\v1;

use App\Http\Requests\Api\LoginIndexRequest;
use App\Http\Requests\Api\UserRegisterRequest;
use App\Models\User;
use App\Services\VerificationCode;
use Illuminate\Auth\RequestGuard;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Hash;
use App\Http\Resources\Api\UserResource;
use App\Models\RememberToken;

class UserController extends Controller
{
    const VERIFY_CODE_ACTION = [
        VerificationCode::USER_REGISTER => "_register",
        VerificationCode::USER_LOGIN => "_login",
        VerificationCode::PASSWORD_FORGET => "_password_forget",
        VerificationCode::PASSWORD_RESET => "_password_reset",
    ];

    /**
     * 用户注册
     * @param UserRegisterRequest $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function store(UserRegisterRequest $request)
    {
        $verifyData = \Cache::get($request->verification_key);

        if (!$verifyData) {
            return static::failure('422', __('验证码已失效'));
        }

        if (!hash_equals($verifyData['code'], $request->verification_code)) {
            return static::failure('401', __('验证码错误'));
        }

        $user = User::create([
            'mobile' => $verifyData['mobile'],
        ]);

        // 清除验证码缓存
        \Cache::forget($request->verification_key);

        $data = $this->respondWithToken($user);

        return static::success(["user" => new UserResource($user), "token" => $data], __('用户注册成功'));
    }

    public function verifyCode(Request $request)
    {
        $params = $request->input(["mobile", "type", "code"]);
        isset(self::VERIFY_CODE_ACTION[$params["type"]]) ?
            $action = self::VERIFY_CODE_ACTION[$params["type"]] :
            $action = null;
        if ($action) {
            if ($error = VerificationCode::verify($params)) {
                return self::failure($error["code"], __($error["msg"]));
            }
            return $this->$action($request);
        }
        return self::failure(403, __("验证码类型错误"));
    }

    private function _register(Request $request)
    {
        $user = User::query()->create([
            "mobile" => $request->input("mobile"),
        ]);

        return $this->respondWithToken($user);
    }

    private function _login(Request $request)
    {
        $user = User::query()
            ->where("mobile", $request->input("mobile"))
            ->first();

        return $this->respondWithToken($user);
    }

    private function _password_forget(Request $request)
    {
        return $this->setPassword($request);
    }

    private function _password_reset(Request $request)
    {
        return $this->setPassword($request);
    }

    public function setPassword(Request $request)
    {
        return self::success($request);
    }

    public function loginIndex(LoginIndexRequest $request)
    {
        $user = User::where('mobile', $request->mobile)->first();

        if (!$user) {
            return static::failure(404, __("用户不存在"));
        }

        if (!Hash::check($request->pass, $user->password)) {
            return static::failure('400', __('密码错误'));
        }

        return $this->respondWithToken($user);
    }

    protected function respondWithToken($user)
    {
        if (is_null($user->password)) {
            return self::failure(202, __("请设置密码"));
        }

        $token = token($user);
        $login_ip = ip2long(\request()->getClientIp());
        $data = [
            'access_token' => $token,
            'token_type' => '',
        ];

        try {
            RememberToken::token($token, $user->id, $login_ip);
        } catch (\Exception $exception) {
            return self::failure(500, __("系统错误"));
        }

        return static::success([
            "user" => new UserResource($user),
            "token" => $data
        ], __('登录成功'));
    }
}
